package thinker.miracle.interceptor;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.web.filter.OncePerRequestFilter;

/**
 * 过滤器
 * @author chenbo
 *
 *	web应用时调用的拦截器
 *	
 *	推荐使用  WebInterceptor拦截
 *
 */
@Deprecated
public class SessionFilter extends OncePerRequestFilter {

	protected Logger logger = Logger.getLogger(this.getClass());
	
	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	protected void doFilterInternal(HttpServletRequest request,
			HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {	
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		HttpSession session = ((HttpServletRequest)request).getSession();
		// 获取URL
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		String uri = httpRequest.getRequestURL().toString();
		FilterConfig config = getFilterConfig();
		if (uri == null || uri.trim().length() == 0) {
			return;
		}
		//止后缀无需过滤，配置的资源文件
        String suffix = config.getInitParameter("suffix");
		String[] suffixList = suffix.split(";");
		logger.info(uri);
		if (contains(uri, suffixList)) {
			filterChain.doFilter(request, response);
			return;
		}
		//判断是否登陆
		Object userInfoObj = session.getAttribute("userInfo");
		if(null == userInfoObj){
			request.getRequestDispatcher("/userInfo/login").forward(request,response);
			return;
		}
        filterChain.doFilter(request, response);
	}

	
	/**
	 * @param container
	 * @param regx
	 * @return
	 */
	protected boolean contains(String container, String[] regx) {
		boolean result = false;
		for (int i = 0; i < regx.length; i++) {
			regx[i] = regx[i].trim();
			if (container.indexOf(regx[i]) != -1) {
				result = true;
			}
		}
		return result;
	}
}
